Page({
  data: {
    orderList: [],
    statusMap: {
      pending: '待支付',
      processing: '进行中',
      completed: '已完成',
      cancelled: '已取消'
    },
    currentStatus: 'processing', // 默认显示进行中的订单
    statusList: [
      { value: 'processing', text: '进行中' },
      { value: 'pending', text: '待支付' },
      { value: 'completed', text: '已完成' },
      { value: 'cancelled', text: '已取消' }
    ]
  },
  onLoad() {
    wx.setNavigationBarTitle({
      title: '进度查询'
    });
  },
  onShow() {
    this.fetchOrders();
  },
  // 切换订单状态
  onStatusChange(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({ currentStatus: status });
    this.fetchOrders();
  },
  fetchOrders() {
    const userId = wx.getStorageSync('userId');
    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    wx.showLoading({ title: '加载中...' });
    const app = getApp();
    app.request({
      url: `/api/orders/user/${userId}/status/${this.data.currentStatus}`,
      method: 'GET'
    })
      .then(res => {
        this.setData({ orderList: res.data || [] });
        wx.hideLoading();
      })
      .catch(err => {
        console.error('获取订单列表失败:', err);
        wx.showToast({
          title: '获取订单列表失败',
          icon: 'none'
        });
        this.setData({ orderList: [] });
        wx.hideLoading();
      });
  },
  viewDetail(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/orderDetail/orderDetail?orderId=${orderId}`
    });
  },
  payOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    // 获取订单金额
    const order = this.data.orderList.find(order => order.orderId === orderId);
    if (!order) {
      wx.showToast({
        title: '订单信息获取失败',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '确认支付',
      content: `确定要支付该订单吗？金额：￥${order.totalAmount}`,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '支付中...' });
          const app = getApp();
          // 先进行支付
          app.request({
            url: `/api/orders/${orderId}/pay`,
            method: 'POST',
            data: {
              amount: order.totalAmount // 使用订单实际金额
            }
          })
            .then(() => {
              // 支付成功后，更新订单状态
              return app.request({
                url: `/api/orders/${orderId}/status?status=processing`,
                method: 'PUT'
              });
            })
            .then(() => {
              wx.hideLoading();
              wx.showToast({
                title: '支付成功',
                icon: 'success'
              });
              // 刷新订单列表
              this.fetchOrders();
            })
            .catch(err => {
              wx.hideLoading();
              wx.showToast({
                title: '操作失败',
                icon: 'none'
              });
            });
        }
      }
    });
  },
  cancelOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认取消',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          const app = getApp();
          app.request({
            url: `/api/orders/${orderId}/cancel`,
            method: 'PUT'
          })
            .then(() => {
              wx.showToast({
                title: '订单已取消',
                icon: 'success'
              });
              this.fetchOrders();
            })
            .catch(err => {
              console.error('取消订单失败:', err);
              wx.showToast({
                title: '取消订单失败',
                icon: 'none'
              });
            });
        }
      }
    });
  },
  reviewOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/review/review?orderId=${orderId}`
    });
  },
  goChat(e) {
    const orderId = e.currentTarget.dataset.id;
    const userId = wx.getStorageSync('userId');
    wx.navigateTo({
      url: `/pages/chat/chat?orderId=${orderId}&userId=${userId}`
    });
  }
}); 